import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
import '../../static/css/icon-font/iconfont.css';
import './index.scss';

import { searchApi } from '../../utils/http';
import SongsList from '../songsList/songsList';

export default function Index() {
    // []获取值：自定义两个变量名，取值结果与顺序有关
    const [songsList, setSongList] = useState([]); // 引入变量songsList=[];引入改变这个变量的函数setSongList
    let keyWord = '',
        navigate = useNavigate();
    // 点击搜索
    function search() {
        searchApi(keyWord).then(res => {
            if (res.data.code === 200) {
                setSongList(res.data.result.songs)
            }
        })
    }
    // 回车搜索
    function enterSearch(e) {
        if(e.keyCode === 13){
            search();
        }
    }
    // 输入框内容发生变化改变关键词的值
    function changeKeyWords(e) {
        keyWord = e.target.value;
    }
    function toLogin() {
        navigate('/login');
    }
    // 点击去详情
    function todetails(e, song) {
        navigate('/index/details', { state: { song: song } })
    }
    // 补零函数
    function addZero(num) {
        return num < 10 ? '0' + num : '' + num;
    }
    return (
        <div className='index'>
            <div className='topSearch'>
                <input 
                    type="text" 
                    className='iconfont searchInput' 
                    placeholder='&#xe7b3; 请输入关键字' 
                    onKeyUp={(e) => enterSearch(e)} 
                    onChange={(e) => changeKeyWords(e)} 
                />
                <button className='searchBtn' onClick={() => search()}><span className='iconfont'>&#xe7b3;</span></button>
                
            </div>
            <SongsList songsList={songsList}></SongsList>
            <button className='toLogin' onClick={() => toLogin()}>去登陆</button>
        </div>
    )
}